package com.example.k8s.hello.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
public class JsonUtils {

    public static final ObjectMapper objectMapper = new ObjectMapper();

    public static String toJsonString(Object value) {
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("json序列化失败", e);
        }
    }

    public static <T> T parseObject(String str, Class<T> cClass) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }

        try {
            return objectMapper.readValue(str, cClass);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("json反序列化失败", e);
        }
    }
    public static <T> T parseObject(String str, JavaType javaType) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }

        try {
            return objectMapper.readValue(str, javaType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("json反序列化失败", e);
        }
    }

    public static <T> List<T> parseArray(String str, Class<T[]> clazz){
        if (StringUtils.isEmpty(str)) {
            return Collections.emptyList();
        }

        T[] result = null;
        try {
            result = objectMapper.readValue(str, clazz);
        } catch (Exception e) {
            throw new RuntimeException("json反序列化失败", e);
        }
        if (result == null) {
            return Collections.emptyList();
        }
        return Arrays.asList(result);
    }

    public static JsonNode parseJson(String str) {
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(str);
        } catch (Exception e) {
            throw new RuntimeException("json反序列化失败", e);
        }
        return jsonNode;
    }
}
